import AddForm from '@/pages/BusinessPageList/components/AddForm';
import SqlConfigListDrawer from '@/pages/BusinessPageList/components/SqlConfigListDrawer';
import {businessPageList, deleteBusinessPage, globalReloadRule} from '@/services/wms-dev-tool/business-page-list';
import { useRequest } from '@@/plugin-request';
import {PlusOutlined, ReloadOutlined} from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable, TableDropdown } from '@ant-design/pro-components';
import { Link } from '@umijs/max';
import { Button, message, Modal, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import UpdateForm from './components/UpdateForm';
import RuleScriptNodeListDrawer from './components/RuleScriptNodeListDrawer';
import RuleChainListDrawer from "@/pages/BusinessPageList/components/RuleChainListDrawer";

const BusinessPageList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateFormOpen, handleUpdateFormOpen] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.BusinessPage>();

  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    console.log('handleTableChange-------------->', pagination, filters, sorter);
  };

  const [addFormOpen, handleAddFormOpen] = useState<boolean>(false);

  const [sclDrawerOpen, handleSclDrawerOpen] = useState<boolean>(false);
  const [configAddrModalOpen, handleConfigAddrModalOpen] = useState<boolean>(false);

  const [rsnDrawerOpen, handleRsnDrawerOpen] = useState<boolean>(false);
  const [rcDrawerOpen, handleRcDrawerOpen] = useState<boolean>(false);

  //刷新表格
  const refreshTable = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };
  const { run: delRun } = useRequest(deleteBusinessPage, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功');
      refreshTable();
    },
  });

  const copyToClipboard = (text: string) => {
    navigator.clipboard
      .writeText(text)
      .then(() => {
        message.success('复制成功');
      })
      .catch((error) => {
        console.error('复制到剪贴板时出错:', error);
      });
  };

  const handleAddrCopy = () => {
    copyToClipboard(`/lowCode/amisRenderer/${currentRow?.id}/` + '${sqlCode}');
    handleConfigAddrModalOpen(false);
  };

  //定义表格的数据列
  const columns: ProColumns<API.BusinessPage>[] = [
    {
      title: <span>名称</span>,
      dataIndex: 'name',
      search: {
        transform: (value) => {
          return { name: `*${value}*` };
        },
      },
    },
    {
      title: <span>编码</span>,
      dataIndex: 'code',
      search: {
        transform: (value) => {
          return { code: `*${value}*` };
        },
      },
    },
    {
      title: <span>创建时间</span>,
      dataIndex: 'createTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: <span>更新时间</span>,
      dataIndex: 'updateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: <span>操作</span>,
      dataIndex: 'option',
      valueType: 'option',
      render: (dom, record) => [
        <a
          key="edit"
          onClick={() => {
            handleUpdateFormOpen(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Link to={`/page-designer/${record.id}`} target="_blank" key="design">
          设计界面
        </Link>,
        <a
          key="sqlConfig"
          onClick={() => {
            handleSclDrawerOpen(true);
            setCurrentRow(record);
          }}
        >
          SQL配置
        </a>,
        <a
          key="scriptNode"
          onClick={() => {
            handleRsnDrawerOpen(true);
            setCurrentRow(record);
          }}
        >
          组件脚本
        </a>,
        <a
          key="ruleChain"
          onClick={() => {
            handleRcDrawerOpen(true)
            setCurrentRow(record);
          }}
        >
          编排规则
        </a>,
        <TableDropdown
          key="actionGroup"
          menus={[
            {
              key: 'addrConfig',
              name: '配置地址',
              onClick: () => {
                handleConfigAddrModalOpen(true);
                setCurrentRow(record);
              },
            },
            {
              key: 'delete',
              danger: true,
              name: (
                <Popconfirm
                  key="delete"
                  title="提示"
                  description="是否删除该条记录？这将意味着对应界面将无法渲染！"
                  onConfirm={() => delRun(record.id)}
                  okText="是"
                  cancelText="否"
                >
                  <a>删除</a>
                </Popconfirm>
              ),
            },
          ]}
        >
          更多...
        </TableDropdown>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.BusinessPage, API.PageParams>
        headerTitle={<span>业务界面</span>}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        onChange={handleTableChange}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={async () => {
              const {message:msg,success} = await globalReloadRule()
              if(success) {
                message.success(msg)
                return
              }
            }}
          >
            <ReloadOutlined />
            全局刷新规则
          </Button>,
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleAddFormOpen(true);
            }}
          >
            <PlusOutlined />
            新建
          </Button>,
        ]}
        request={businessPageList}
        columns={columns}
      />
      <AddForm
        addFormOpen={addFormOpen}
        handleAddFormOpen={handleAddFormOpen}
        ok={refreshTable}
      ></AddForm>
      <UpdateForm
        updateFormOpen={updateFormOpen}
        handleUpdateFormOpen={handleUpdateFormOpen}
        ok={refreshTable}
        values={currentRow || {}}
      />
      <SqlConfigListDrawer
        sclDrawerOpen={sclDrawerOpen}
        handleSclDrawerOpen={handleSclDrawerOpen}
        payload={{ pageId: currentRow?.id, pageName: currentRow?.name }}
      />
      <RuleScriptNodeListDrawer
        rsnDrawerOpen={rsnDrawerOpen}
        handleRsnDrawerOpen={handleRsnDrawerOpen}
        pageId={currentRow?.id}
      />
      <RuleChainListDrawer
        rcDrawerOpen={rcDrawerOpen}
        handleRcDrawerOpen={handleRcDrawerOpen}
        pageId={currentRow?.id}/>
      <Modal
        open={configAddrModalOpen}
        title="配置地址"
        closable={true}
        onCancel={() => {
          handleConfigAddrModalOpen(false);
        }}
        footer={[
          <Button
            key="cancel"
            onClick={() => {
              handleConfigAddrModalOpen(false);
            }}
          >
            取消
          </Button>,
          <Button key="copy" type="primary" onClick={handleAddrCopy}>
            复制
          </Button>,
        ]}
      >
        <p>
          /lowCode/amisRenderer/{currentRow?.id}/{'${sqlCode}'}
        </p>
      </Modal>
    </PageContainer>
  );
};

export default BusinessPageList;
